﻿//Dùng tại:
//      + frmWaiting
//      + frmConfigDatabase

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.IO;
using DevExpress.XtraEditors;
using prjKQXS_UI.View;
using prjKQXS_DLL;
using prjKQXS_DLL.Dal;
using prjKQXS_DLL.Security;

namespace prjKQXS_UI.Security
{
    public partial class frmLogin : XtraForm
    {
        /// <summary>
        /// Profile.txt
        /// </summary>
        private string path = @"Profile.txt";

        private bool sac = false;

        #region form's event ========================================================
        public frmLogin()
        {
            InitializeComponent();
        }

        private void frmLogin_Shown(object sender, EventArgs e)
        {
            load_cbbServer();
            Config.getConnectionProperties(BienTc.connString, ref BienTc.ServerName, ref BienTc.UserName, ref BienTc.Password);

            if (File.Exists(path))
            {
                chkRemember.Checked = true;
                using (StreamReader sr = File.OpenText(path))
                {
                    teUser.Text = clsCommon.Decrypt(sr.ReadLine().ToString().Trim(), BienTc.encryptString, true);
                    tePass.Text = clsCommon.Decrypt(sr.ReadLine().ToString().Trim(), BienTc.encryptString, true);

                    string s = sr.ReadLine().ToString().Trim();
                    if (s == "") cbbDatabase.SelectedIndex = 0;
                    else cbbDatabase.SelectedValue = clsCommon.Decrypt(s, BienTc.encryptString, true);
                }
            }
        }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!sac)
            {
                Application.Exit();
            }
        }
        #endregion ==================================================================


        #region control's event ======================================================
        private void sbtnThietlap_Click(object sender, EventArgs e)
        {
            frmConfigDatabase config = new frmConfigDatabase(this.Name);
            config.FormClosed += new FormClosedEventHandler(config_FormClosed);
            this.Visible = false;
            config.ShowDialog();
        }

        private void config_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Visible = true;
        }

        private DataTable doLogin(string username, string password)
        {
            try
            {
                SqlConnection conn = new SqlConnection(BienTc.connString);
                conn.Open();

                SqlDataAdapter adapter = new SqlDataAdapter("select * from tblUser where username=@username and password=@password", conn);
                adapter.SelectCommand.Parameters.AddWithValue("@username", username);
                adapter.SelectCommand.Parameters.AddWithValue("@password", password);
                
                DataTable dt = new DataTable();
                adapter.Fill(dt);

                return dt;
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void sbtnLogin_Click(object sender, EventArgs e)
        {
            if (cbbDatabase.SelectedIndex != -1 && cbbDatabase.SelectedValue.ToString() != "System.Data.DataRowView")
            {
                doConnstr();
                if (validateForm())
                {
                    try
                    {
                        DataTable dt = doLogin(teUser.Text.Trim(), clsCommon.Encrypt(tePass.Text.Trim(), BienTc.encryptString, true));
                        if (dt.Rows.Count > 0)
                        {
                            //
                            if (chkRemember.Checked)
                            {
                                if (File.Exists(path)) File.Delete(path);
                                using (StreamWriter sw = File.CreateText(path))
                                {
                                    sw.WriteLine(clsCommon.Encrypt(teUser.Text, BienTc.encryptString, true));
                                    sw.WriteLine(clsCommon.Encrypt(tePass.Text, BienTc.encryptString, true));
                                    sw.WriteLine(clsCommon.Encrypt(cbbDatabase.SelectedValue.ToString(), BienTc.encryptString, true));
                                }
                           }
                            else File.Delete(path);

                            //Gán giá trị cho các biến toàn cục tại BienTc: UserID, userName, pcName, fullname, supervisor, isThanhPho, isQuanHuyen, ma_huyen
                            BienTc.FullName = dt.Rows[0]["FullName"].ToString();
                            BienTc.supervisor = Int32.Parse(dt.Rows[0]["Supervisor"].ToString());

                            sac = true;
                            object oLoaiQD = clsCommon.getCellValue("DONVI", "LoaiQD", "Where isPublic=1");
                            if (oLoaiQD != null)
                            {
                                if (oLoaiQD.ToString() == "TP")
                                {
                                    BienTc.isThanhPho = true;
                                }
                                else if (oLoaiQD.ToString() == "QH")
                                {
                                    BienTc.isQuanHuyen = true;
                                }
                                else if (oLoaiQD.ToString() == "CTY")
                                {
                                    BienTc.isThanhPho = false;
                                    BienTc.isQuanHuyen = false;
                                }
                            }

                            if (oLoaiQD.ToString().Trim().ToUpper() != "CTY")
                            {
                                oLoaiQD = clsCommon.getCellValue("DONVI", "Ma_so_CT", "Where isPublic=1");
                                BienTc.ma_huyen = oLoaiQD.ToString().Trim();
                            }

                            BienTc.UserID = (int)dt.Rows[0]["ID"];
                            BienTc.username = teUser.Text.Trim();
                            BienTc.pcName = clsCommon.getComputerName();

                            frmMain frm = new frmMain();
                            frm.Show();
                            this.Hide();
                        }
                        else clsCommon.MsgBox("Sai tên đăng nhập hoặc mật khẩu. Hãy kiểm tra lại.", 0);
                    }
                    catch (Exception ex)
                    {
                        clsCommon.MsgBox(ex.Message, 0);
                        Config.Errlog("Dang nhap:", ex.Message);
                        Application.Exit();
                    }
                }
            }
            else clsCommon.MsgBox("Bạn chưa chọn cơ sở dữ liệu.", 1);
        }

        private void cbbServer_SelectedIndexChanged(object sender, EventArgs e)
        {
            doConnstr();
        }

        private void sbtnThoat_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion ==================================================================


        #region function ============================================================
        private void load_cbbServer()
        {
            DataTable dtSv = getKQXSDatabase();
            if (dtSv.Rows.Count > 0)
            {
                cbbDatabase.DataSource = dtSv;
                cbbDatabase.DisplayMember = "name";
                cbbDatabase.ValueMember = "name";
                cbbDatabase.SelectedIndex = 0;
            }
            else
            {
                clsCommon.MsgBox("Không có database trong hệ thống.", 1);
            }
        }

        private DataTable getKQXSDatabase()
        {
            DataTable dt = new DataTable("db");
            dt.Columns.Add("name");
            dt.Columns.Add("des");
            string[] s = BienTc.connString.Split(';');//Tách các thành phần của chuỗi connection dựa vào dấu ";"
            string connString = "";
            foreach (string ss in s)
            {
                if (ss.Trim().Contains("Data Source"))
                {
                    if (connString.Equals("")) connString = ss + ";";
                    else connString += ss + ";";
                }
                else if (ss.Trim().Contains("User Id"))
                {
                    if (connString.Equals("")) connString = ss + ";";
                    else connString += ss + ";";
                }
                else if (ss.Trim().Contains("Password"))
                {
                    if (connString.Equals("")) connString = ss + ";";
                    else connString += ss + ";";
                }
            }

            if (!connString.Trim().Equals(""))
            {
                string sql = @"  SELECT name FROM sys.databases 
                        WHERE name not in('master','tempdb','model','msdb', 'ReportServer', 'ReportServerTempDB') 
                            and state_desc = 'ONLINE'";

                DataTable dtTable = clsCommon.FillData(sql);

                //Đoạn này lấy ra các csdl của chương trình bằng cách kiểm tra xem trong csdl tên dr["name"] có bảng tblDesKeToan không.
                SqlConnection conn;
                foreach (DataRow dr in dtTable.Rows)
                {
                    try
                    {
                        string connstrChiTiet = connString + "Initial Catalog=" + dr["name"].ToString() + ";";
                        conn = new SqlConnection(connstrChiTiet);
                        conn.Open();
                        SqlCommand cmd = new SqlCommand("select des from tblDesKeToan WHERE des = 'KQXS' and isPublic = 1", conn);
                        string des = cmd.ExecuteScalar().ToString();
                        dt.Rows.Add(new object[] { dr["name"].ToString(), des });
                    }
                    catch (SqlException ex)
                    {
                        if (ex.Message != "Invalid object name 'tblDesKeToan'.") throw ex;
                    }
                    catch (NullReferenceException ex)
                    {
                        //Bỏ qua
                    }
                }
            }
            return dt;
        }

        private void doConnstr()
        {
            string connStr = "";
            string dataSource = "";
            string userID = "";
            string password = "";
            Config.getConnectionProperties(Config.loadConfig(), ref dataSource, ref userID, ref password);

            if (cbbDatabase.Items.Count > 0)
            {
                if (cbbDatabase.SelectedIndex != -1 && cbbDatabase.SelectedValue.ToString() != "System.Data.DataRowView")
                {
                    connStr = "Data Source=" + dataSource + "; Initial Catalog=" + 
                        cbbDatabase.SelectedValue.ToString() + ";User Id=" + userID + "; Password=" + password + ";";
                    BienTc.dbName = cbbDatabase.SelectedValue.ToString();
                    BienTc.UserName = userID;
                    BienTc.Password = password;
                    if (dataSource != "" && cbbDatabase.SelectedValue.ToString() != "" && userID != "" & password != "")
                    {
                        Config.writeConfig(connStr);
                        BienTc.connString = connStr;
                        BienTc.UserName = userID;
                        BienTc.Password = password;
                    }
                    else
                        clsCommon.MsgBox("Kết nối tới máy chủ bị gián đoạn, hãy thiết lập lại kết nối.", 0);
                }
            }
        }

        private bool validateForm()
        {
            if (teUser.Text.Trim().Length == 0)
            {
                clsCommon.MsgBox("Tên đăng nhập không được để trống!", 0);
                teUser.Focus();
                return false;
            }
            else if (tePass.Text.Trim().Length == 0)
            {
                clsCommon.MsgBox("Mật khẩu không được để trống!", 0);
                teUser.Focus();
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion ==================================================================
    }
}